import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import Router from '@koa/router'
import  TCB, { CloudBase }  from '@cloudbase/node-sdk';    
import axios from 'axios';
import * as https from 'https';
// 初始化各服务的连接 redis, mongo
async function initService() {
   
}
process.env.KUBERNETES_SERVICE_HOST = "";
initService().then(async () => {
    const app = new Koa();
    const router = new Router();
    router.get('/test', async (ctx) => {
        console.log('KUBERNETES_SERVICE_HOST', !!process.env.KUBERNETES_SERVICE_HOST);
        ctx.body = !!process.env.KUBERNETES_SERVICE_HOST;
    }).
    get('/demo',async(ctx) => {
        try {
        const cloud = TCB.init({
            secretId: 'AKIDGLL8qX1Wzc4PXi8W9f0BBSiu1GSn1EOQ',
            secretKey: '9OacWK31prusJ5qaedaP7nMivzFPSPG0',
            env:'test-4ghxsyf43e9de32e'
        });
        const res = await cloud.database().collection('config').count();
      //  console.log('success', res);
        ctx.body = JSON.stringify(res);
        }catch(err) {
            console.error('error', err);
            ctx.body = JSON.stringify(err.message);
        }
    }).get('/api/get_data_from_redis', async(ctx) => {
        try {
            const response = await axios.get('https://www.baidu.com');
            console.log('Response baidu111:', response.data);
            ctx.body = JSON.stringify(response.data);
            // 在这里处理响应
          } catch (error) {
            console.error('Error baidu:111', error);
            ctx.body = JSON.stringify(error.message);
            // 在这里处理错误
          }
    }).get('/api/get_tcb_demo', async(ctx) => {
        try {
            const httpsAgent = new https.Agent({
                rejectUnauthorized: false,
              });
              axios.defaults.httpsAgent = httpsAgent;
            const response = await axios.post(
              'http://test-4ghxsyf43e9de32e.tcb-api.tencentcloudapi.com/admin?content-type=application%2Fjson',
              {
                collectionName: 'config',
                queryType: 'WHERE',
                action: 'database.calculateDocument',
                envName: 'test-4ghxsyf43e9de32e',
                eventId: '190c1387e09_1',
                wxCloudApiToken: '',
                wxCloudbaseAccesstoken: '',
                tcb_sessionToken: '',
                crossAuthorizationToken: '',
              },
              {
                headers: {
                  'Content-Type': 'application/json',
                  'User-Agent': 'tcb-node-sdk/2.11.0',
                  'x-client-timestamp': '1721228623369',
                  'X-SDK-Version': 'tcb-node-sdk/2.11.0',
                  'Host': 'test-4ghxsyf43e9de32e.tcb-api.tencentcloudapi.com',
                  'Authorization': 'TC3-HMAC-SHA256 Credential=AKIDMitFfHskYFxb4NYdZajwAbzSxQAworyy/2024-07-17/tcb/tc3_request, SignedParams=action;collectionname;crossauthorizationtoken;envname;eventid;querytype;tcb_sessiontoken;wxcloudapitoken;wxcloudbaseaccesstoken, SignedHeaders=content-type;host;user-agent;x-client-timestamp;x-sdk-version;x-tcb-source, Signature=eef109b79f63987c9f74bef3cff6acb2ed2e8ab9f9328da963eb3aaaa2ea9b60',
                  'X-Signature-Expires': '600',
                  'X-Timestamp': '1721228622',
                },
              }
            );
        
            console.log('Response tcb demo:', response.data);
            ctx.body = JSON.stringify(response.data);
            // 在这里处理响应
          } catch (error) {
            console.error('Error tcb demo:', error.message);
            ctx.body = JSON.stringify(error.message);
            // 在这里处理错误
          }
        
    });

    app.use(bodyParser());
    app.use(router.routes());

    const PORT = 8000;
    app.listen(PORT, () => {
        console.log(`Server running on port ${PORT}`);
    });

}).catch((error: string) => console.log("Init service  error: ", error));